const cache = require('@/utils/cache.js')
const request = require('@/utils/request.js')
const { useUserInfoSubmitApi, useUserAvatarApi } = require('@/api/user.js')

Page({
  data: {
    user: {
      id: '',
      avatar: '',
      username: '',
      gender: 0
    },
    genderVisible: false,
    genderList: [
      { label: '男', value: 1 },
      { label: '女', value: 0 }
    ],
    genderMap: ['女', '男']
  },
  onShow() {
    const userInfo = cache.getUserInfo();
    if(userInfo) {
      const newUser = {
        username: userInfo.username,
        avatar: userInfo.avatar,
        id: userInfo.id,
        openId: userInfo.openId,
        gender: userInfo.gender
      }
      this.setData({
        user: newUser
      })
    }
  },
  onChooseAvatar(e) {
    console.log(e, 'eee');
    const { avatarUrl } = e.detail;
    const newUser = this.user;
    newUser.avatar = avatarUrl;
    this.setData({
      user: newUser
    })
  },
  async uploadAvatar() {
    // 获取选择的头像路径
    const tempFilePath = await new Promise((resolve, reject) => {
      wx.chooseMedia({
        mediaType: ['image'],
        count: 1,
        success: (res) => {
          resolve(res.tempFiles[0].tempFilePath)
        },
        fail: (err) => reject(err)
      })
    })

    // 上传头像
    const { data } = await request.upload('/sys/file/upload', tempFilePath)

    // 修改用户头像
    await useUserAvatarApi({ avatar: data.url })
    this.data.user.avatar = data.url
    this.setData({ user: this.data.user })
    cache.setUserInfo(this.data.user)
  },
  onGenderOpen() {
    this.setData({ genderVisible: true })
  },
  onGenderCancel() {
    this.setData({ genderVisible: false })
  },
  onGenderChange(e) {
    const { value } = e.detail
    this.data.user.gender = value[0]
    this.setData({
      genderVisible: false,
      user: this.data.user
    })

    useUserInfoSubmitApi(this.data.user).then(() => {
      cache.setUserInfo(this.data.user)
    })
  }
})
